import { NextRequest, NextResponse } from 'next/server';
import acceptLanguage from 'accept-language';
import { fallbackLng, languages, cookieName } from './i18n';

// 告诉 accept-language 库我们支持的语言列表
acceptLanguage.languages(languages);

export const config = {
	// 定义中间件的 matcher 配置
	matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)']
};

// PC和移动端路径映射配置
const getRouteMappings = (lng: string) => [
	[`/${lng}`, `/${lng}/mobile`],
	[`/${lng}/about`, `/${lng}/mobile/about`]
];

// 动态路由模式配置
const getDynamicRouteMappings = (lng: string) => [
	{
		pcPattern: new RegExp(`^/${lng}/about/(.+)$`),
		mobilePattern: new RegExp(`^/${lng}/mobile/about/(.+)$`),
		pcTemplate: `/${lng}/about/`,
		mobileTemplate: `/${lng}/mobile/about/`
	}
];

// 设备检测函数 - 修复服务器端兼容性问题
const detectDevice = (userAgent: string) => {
	const ua = userAgent.toLowerCase();

	return {
		trident: ua.includes('trident'), // IE内核
		presto: ua.includes('presto'), // Opera内核
		webKit: ua.includes('applewebkit'), // 苹果、谷歌内核
		gecko: ua.includes('gecko') && !ua.includes('khtml'), // 火狐内核
		mobile:
			/mobile|android|iphone|ipad|phone|blackberry|opera mini|opera mobi|skyfire|maemo|windows phone|palm|iemobile|symbian|symbos|fennec/.test(
				ua
			),
		ios: /iphone|ipad|ipod/.test(ua),
		android: ua.includes('android'),
		iPhone: ua.includes('iphone'),
		iPad: ua.includes('ipad'),
		webApp: !ua.includes('safari'),
		weixin: ua.includes('micromessenger')
	};
};

// 获取语言代码
const getLanguageCode = (req: NextRequest): string => {
	// 1. 优先从 cookie 获取
	if (req.cookies.has(cookieName)) {
		const cookieValue = req.cookies.get(cookieName)?.value;
		const lng = acceptLanguage.get(cookieValue);
		if (lng) return lng;
	}

	// 2. 尝试从 referer 获取
	if (req.headers.has('referer')) {
		const refererUrl = new URL(req.headers.get('referer') || '');
		const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`));
		if (lngInReferer) return lngInReferer;
	}

	// 3. 从 Accept-Language 头部获取
	const acceptLng = acceptLanguage.get(req.headers.get('Accept-Language'));
	if (acceptLng) return acceptLng;

	// 4. 使用默认语言
	return fallbackLng;
};

// 创建重定向响应
const createRedirect = (url: string, search: string, req: NextRequest): NextResponse => {
	return NextResponse.redirect(new URL(url + search, req.url));
};

// 检查路径是否需要重定向
const getRedirectPath = (pathname: string, lng: string, isMobile: boolean) => {
	// 首先检查静态路由映射
	const routeMappings = getRouteMappings(lng);
	const mapping = routeMappings.find(([pc, mobile]) => (isMobile ? pc === pathname : mobile === pathname));

	if (mapping) {
		return isMobile ? mapping[1] : mapping[0]; // 返回目标路径
	}

	// 然后检查动态路由映射
	const dynamicMappings = getDynamicRouteMappings(lng);
	for (const { pcPattern, mobilePattern, pcTemplate, mobileTemplate } of dynamicMappings) {
		if (isMobile) {
			// 移动端访问，检查是否匹配PC模式，如果匹配则重定向到移动端
			const pcMatch = pathname.match(pcPattern);
			if (pcMatch) {
				const id = pcMatch[1];
				return mobileTemplate + id;
			}
		} else {
			// PC端访问，检查是否匹配移动端模式，如果匹配则重定向到PC端
			const mobileMatch = pathname.match(mobilePattern);
			if (mobileMatch) {
				const id = mobileMatch[1];
				return pcTemplate + id;
			}
		}
	}

	return null;
};

// 主中间件函数
export function middleware(req: NextRequest) {
	const userAgent = req.headers.get('user-agent') || '';
	const device = detectDevice(userAgent);
	const isMobile = device.mobile;

	const { pathname, search } = req.nextUrl;
	const lng = getLanguageCode(req);

	// 处理没有语言前缀的路径
	const hasLanguagePrefix = languages.some((lang) => pathname.startsWith(`/${lang}`));
	const isNextRoute = pathname.startsWith('/_next') || pathname.startsWith('/.well-known');

	if (!hasLanguagePrefix && !isNextRoute) {
		const routeMappings = getRouteMappings(lng);
		const hasMapping = routeMappings.some(([pc, mobile]) => pc.endsWith(pathname) || mobile.endsWith(pathname));

		if (hasMapping) {
			const targetPath = isMobile ? `/${lng}/mobile${pathname}` : `/${lng}${pathname}`;
			return createRedirect(targetPath, search, req);
		} else {
			// 检查动态路由模式
			const dynamicMappings = getDynamicRouteMappings(lng);
			const hasDynamicMapping = dynamicMappings.some(({ pcTemplate, mobileTemplate }) => {
				const pcBase = pcTemplate.replace(`/${lng}/`, '/');
				const mobileBase = mobileTemplate.replace(`/${lng}/mobile`, '/');
				return pathname.startsWith(pcBase) || pathname.startsWith(mobileBase);
			});

			if (hasDynamicMapping) {
				const targetPath = isMobile ? `/${lng}/mobile${pathname}` : `/${lng}${pathname}`;
				return createRedirect(targetPath, search, req);
			} else {
				return createRedirect(`/${lng}${pathname}`, search, req);
			}
		}
	}

	// 处理PC/移动端路径切换
	const redirectPath = getRedirectPath(pathname, lng, isMobile);
	if (redirectPath && redirectPath !== pathname) {
		return createRedirect(redirectPath, search, req);
	}

	// 设置语言cookie（如果需要）
	const response = NextResponse.next();
	if (req.headers.has('referer')) {
		const refererUrl = new URL(req.headers.get('referer') || '');
		const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`));
		if (lngInReferer) {
			response.cookies.set(cookieName, lngInReferer);
		}
	}

	return response;
}
